package com.phonetools.commonutils.android.hardware

import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import android.provider.Settings
import com.phonetools.commonutils.android.getTelephonyManager
import java.net.NetworkInterface
import java.net.SocketException
import java.util.*

/**
 * 获取Mac地址
 * @return Mac地址字符串
 */
fun getMacAddress(): String {
    try {
        val allInfo = Collections.list(NetworkInterface.getNetworkInterfaces())

        allInfo.forEach {
            if (it.name.equals("wlan0", ignoreCase = true)) {
                val macBytes = it.hardwareAddress ?: return ""
                val stringBuilder = StringBuilder()
                if (macBytes.isNotEmpty()) {
                    macBytes.forEach { macByte ->
                        stringBuilder.append(String.format("%02X:", macByte))
                    }
                }

                if (stringBuilder.isNotEmpty()) {
                    stringBuilder.deleteCharAt(stringBuilder.length - 1)
                }

                return stringBuilder.toString()
            }
        }

    } catch (e: SocketException) {
        e.printStackTrace()
    }

    return ""
}

/**
 * 获取设备ID号
 */
@SuppressLint("MissingPermission", "HardwareIds")
fun getDeviceId(context: Context): String {
    return try {
        getTelephonyManager(context).deviceId
    } catch (e: Exception) {
        e.printStackTrace()
        ""
    }
}

@SuppressLint("HardwareIds")
fun getAndroidID(context: Context): String {
    return try {
        Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID)
    } catch (e: Exception) {
        e.printStackTrace()
        ""
    }
}

fun getImei(context: Context): String {
    return try {
        val tm = getTelephonyManager(context)
        val getImei = tm.javaClass.getDeclaredMethod("getImei", Integer.TYPE)
        getImei.invoke(tm, 0) as String
    } catch (e: Exception) {
        e.printStackTrace()
        ""
    }
}

/**
 * 获取序列号(点聚SDK)
 */
fun getSerialNo(context: Context): String {
    var serialNo = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        getAndroidID(context)
    } else {
        getImei(context)
    }

    if (serialNo.isEmpty()) {
        serialNo = getDeviceId(context)
    }

    if (serialNo.isEmpty()) {
        serialNo = getMacAddress()
    }

    return serialNo
}